# -*- coding:utf-8 -*-
"""
@FileName  :gateway.py
@Time      :2022/7/5 11:29
@Author    :fsksf
"""


import json
from typing import Optional, Awaitable

from pyrestful.rest import get, post, put, delete
from pyrestful import mediatypes
from vcat.server.base_handler import BaseResource

from vcat.server.routes import ALL_ROUTES
from vcat.utils.api_util import add_handler
from vcat.server.status_code import make_response, Code
from vcat.server.server import app
from vcat.server import TABLE_METAS, BROKER_METAS


@add_handler
class NormalAPIResource(BaseResource):

    def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
        pass


    @get(_path='/api/gateway/meta', _types=[dict],
         _catch_fire=True, _produces=mediatypes.APPLICATION_JSON,
         _consumes=mediatypes.APPLICATION_JSON)
    def broker_meta(self, name):
        # 获取额外的路由信息
        name = name.decode()
        return make_response(code=Code.OK, data=BROKER_METAS.get(name))

    @post(_path='/api/gateway/login', _types=[dict],
          _catch_fire=True, _produces=mediatypes.APPLICATION_JSON,
          _consumes=mediatypes.APPLICATION_JSON)
    def broker_login(self, *args):
        data = args[0]
        print('----data----',data)
        broker_name = data.pop('brokerName')
        app.engine.connect_gateway(broker_name=broker_name,
                               params=data)
        return make_response(code=Code.OK)